package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"three/api/request"
	"three/consts"
	"three/internal/dao"
	"three/internal/model"
	"three/internal/utills"
	jwt "three/pkg"
)

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	user := dao.FindPhone(req.Phone)
	if user.Id == 0 {
		user = model.Users{
			Phone:    req.Phone,
			Password: utills.Pwd(req.Password),
		}
		if !dao.Create(&user) {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "注册失败",
				"data": nil,
			})
			return
		}
		token, _ := jwt.NewJWT(consts.JWT_SECRET_KET).CreateToken(jwt.CustomClaims{
			ID: user.Id,
		})
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "ok",
			"data": token,
		})
		return
	}
	if user.Password != utills.Pwd(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, _ := jwt.NewJWT(consts.JWT_SECRET_KET).CreateToken(jwt.CustomClaims{
		ID: user.Id,
	})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": token,
	})
	return
}
